package com.example.awtDraw;


import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * @Author 郅占伟
 * @ClassName MyPanel
 * @Description TODO
 * @Date 2024年05月14日
 * @Version: 1.0
 */
public class MyPanel extends Panel {
    public static final String VERIFY_CODE = "0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";

    public void paint(Graphics graphics){
        int width = 400;    // 定义验证码图片的宽度
        int height = 300;   // 定义验证码图片的高度

        graphics.setColor(Color.LIGHT_GRAY);        // 设置上下文颜色
        graphics.fillRect(0,0,width,height);    // 填充验证码背景
        graphics.setColor(Color.blue);              // 设置上下文颜色
        graphics.drawRect(0,0,width-1,height-1);        // 绘制边框

        // 绘制干扰点
        Random random = new Random();
        for (int i = 0; i < 100; i++) {
            int startX = random.nextInt(width) - 2;
            int startY = random.nextInt(height) - 2;

            int endX = random.nextInt(width) - 2;
            int endY = random.nextInt(height) - 2;
            //graphics.drawOval(startX,startY,2,2);
            graphics.drawLine(startX,startY,endX,endY);
        }
        graphics.setFont(new Font("宋体", Font.BOLD,60));
        graphics.setColor(Color.red);

        // 产生随机验证码
        char[] charArray = VERIFY_CODE.toCharArray();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            int pos = random.nextInt(charArray.length);
            char c = charArray[pos];
            stringBuilder.append(c).append(" ");
        }

        graphics.drawString(stringBuilder.toString(),20,100);

    }
}
